<!-- 角色管理 -->
<template>
    <div class="common-layout">
        <el-backtop :bottom="50" target=".main" ref="backTop" :visibility-height="10"></el-backtop>
        <el-container>
            <el-header>
                <el-space>
                    <el-input class="fix_input" v-model.trim="seacherData" type="text" autocomplete="off"
                        placeholder="请输入管理员名称" clearable @clear="init()"/>
                    <el-button :icon="Search" type="primary"  @click="searchAdminName()">查找</el-button>
                    <el-button :icon="Edit" type="primary" @click="addRole();">添加</el-button>
                </el-space>
            </el-header>
            <el-main>
                <div class="el-scrollbar__wrap metaBox">
                    <el-backtop :bottom="100" ref="backTop" :visibility-height="5" target=".metaBox .el-scrollbar__wrap" />
                    <!-- 表格组件 -->
                    <el-table :data="tableData" border style="width: 100%;height: 100%;" class="scrollbar-demo-item" v-loading="listLoading" element-londing-text="正在加载中...">
                        <el-table-column prop="id" label="管理员ID" />
                        <el-table-column prop="username" label="管理员名称" />
                        <el-table-column prop="realname" label="真实姓名" />
                        <el-table-column prop="phone" label="电话" />
                        <el-table-column prop="roleIds" label="管理员角色">
                            <template #default="scope">
                                <span v-for="item in roleData" :key="item.value">
                                    <span v-for="items in scope.row.roleIds" :key="items">
                                        <el-tag v-if="item.value == items" style="margin:5px">{{ item.label }}</el-tag>
                                    </span>
                                </span>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作">
                            <template #default="scope">
                                <div>
                                    <el-button type="primary" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
                                    <el-button type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </el-main>
            <el-footer>
                <Paging v-bind="pagination" @page-change="pageChange" />
            </el-footer>
        </el-container>
    </div>

    <!-- 对话框组件 -->
    <el-dialog v-model="dialogVisible" :title="dialog_title" width="60%" :before-close="handleClose" destroy-on-close>
        <!-- 修改功能表单组件 -->
        <el-form ref="ruleFormRef" :model="form" status-icon :rules="rules" class="demo-ruleForm" label-width="200px">
            <el-form-item prop="username" label="用户名：">
                <el-input class="fix_input" v-model.trim="form.username" type="text" autocomplete="off"
                    :disabled="dialog_title == '编辑'" placeholder="请输入用户名" />
            </el-form-item>
            <el-form-item prop="password" label="密码：" v-if="dialog_title == '创建'">
                <el-input class="fix_input" v-model.trim="form.password" type="password" autocomplete="off"
                    placeholder="请输入密码" />
            </el-form-item>
            <el-form-item prop="phone" label="手机号：">
                <el-input class="fix_input" v-model.trim="form.phone" type="text" autocomplete="off" placeholder="请输入手机号" />
            </el-form-item>
            <el-form-item prop="realname" label="真实姓名：">
                <el-input class="fix_input" v-model.trim="form.realname" type="text" autocomplete="off"
                    placeholder="请输入真实姓名" />
            </el-form-item>
            <el-form-item prop="roleIds" label="角色：">
                <el-select multiple style="width: 250px" v-model="form.roleIds">
                    <el-option v-for="item in roleData" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item label-width="75%">
                <el-button type="primary" @click="sure(ruleFormRef)">{{ dialog_title == '创建' ? '新增' : '修改' }}</el-button>
                <el-button @click="resetForm(ruleFormRef)">重置</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
</template>
  
<script lang="ts" setup>
import { Search, Edit } from '@element-plus/icons-vue'
import { ElMessageBox, type FormInstance } from 'element-plus'
import { post } from '@/utils/http';
import { nextTick, onMounted, reactive, ref } from 'vue';
import Paging from '@/components/paging/Paging.vue'
import { ClassPagination } from '#/index';
import { ElMessage } from "element-plus"

// 数据初始化
onMounted(() => {
    init()
})

// 控制对话框组件的显示隐藏
const dialogVisible = ref(false)
const seacherData = ref('')
const backTop = ref()                                   //回到顶部
const pagination = reactive(new ClassPagination())      //分页
let tableData: TypeAdmin[] = reactive([])               //表格数据
let roleData: TypeRoleData[] = reactive([])             //角色数据
let dialog_title = ref()            //对话框的标题
let listLoading = ref(false)            //加载效果
// 修改和添加的数据
let form = reactive({
    username: '',//管理员名称
    password: '',//密码
    phone: '', //电话
    realname: '',//真实姓名
    roleIds: [],//角色
    state: 0        //0:修改    1:新增
})


/**
 * 获取初始化数据，用于渲染页面
 */
function init() {
    listLoading.value = true
    let data = reactive({
        _gp: "admin.role",
        _mt: "options"
    })
    // 请求角色枚举接口拿到角色信息
    post(data).then(res => {

        let { errmsg, data: { total, data },errno } = res
        if (200 == errno) {
            let item = data
            roleData = item
        } else {
            ElMessage.error(errmsg)
        }
    }).then(() => {
        // 请求管理员列表接口拿到管理员列表信息
        let data = reactive({
            _gp: "admin",
            _mt: "list",
            username: seacherData.value,
            page: pagination.page,//当前页码
            limit: pagination.limit//每页页码长度
        })
        post(data).then(res => {
            console.log(res.data.data);
            let { data: { total, items },errno,errmsg } = res
            if (200 === errno) {
                pagination.total = total
                tableData.length = 0;
                tableData.push(...items)
                listLoading.value = false
                nextTick(() => {
                    backTop.value.$el.click?.()
                })
            } else {
                ElMessage.error(errmsg)
            }
        })
    })

}

const ruleFormRef = ref<FormInstance>()

/**
 * 子传父的自定义事件
 * @param e 子传父的事件源
 */
function pageChange(e: TypePage) {
    pagination.page = e.page
    pagination.limit = e.limit
    init()
}


/**
 * 点击搜索
 */
function searchAdminName() {
    init()
}

/**
 * 添加和修改功能
 * @param formEl 表单验证结果
 */
function sure(formEl: FormInstance | undefined) {

    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            console.log("=====要提交的表单数据=====");
            console.log(form);

            let data = {
                _gp: 'admin',
                _mt: form.state ? 'create' : 'edit',
                adminDTO: JSON.stringify(form)
            }
            post(data).then(res => {
                let { errno } = res
                if (200 === errno) {
                    dialogVisible.value = false
                    ElMessage.success(form.state ? '添加成功' : '修改成功')
                    init()
                }
                resetForm(formEl)
            }).catch(err => {
                console.log(err);
            })
        } else {
            return false
        }
    })
}


/**
 * 删除功能
 * @param index 当前下标
 * @param row 当前下标的数据
 */
const handleDelete = (index: number, row: TypeAdmin) => {
    // console.log(index, row)
    ElMessageBox.confirm('真的要删除吗？')

}

// 添加临时数据初始值，用于修改操作重置会原来的数据
const froms = reactive({
    id: 0,
    username: "",
    password: "",
    phone: "",
    realname: "",
    roleIds: []
})


/**
 * 添加按钮
 */

function addRole() {
    dialog_title.value = '创建'
    dialogVisible.value = true;
    Object.assign(froms, form)
    console.log(form);

}

/**
 * 获取修改前的数据
 * @param index 当前下标
 * @param row 当前下标的数据
 */
const handleEdit = (index: number, row: TypeAdmin) => {
    console.log(row)
    dialog_title.value = '编辑'
    dialogVisible.value = true;
    Object.assign(form, row)
    Object.assign(froms, form)
    console.log(form);

}

/**
 * 表单重置
 * @param formEl 表单验证结果
 */
function resetForm(formEl: FormInstance | undefined) {
    if (!formEl) return
    console.log(form, froms);

    formEl.resetFields()
    Object.assign(form, froms)

}

/**
 * 对话框组件的关闭
 * 添加和修改的表单数据不冲突
 */
const handleClose = (done: () => void) => {
    done()

    form.username = '';//管理员名称
    form.password = '';//密码
    form.phone = ''; //电话
    form.realname = '';//真实姓名
    form.roleIds = [];//角色
    form.state = 0;      //0:修改    1:新增

    froms.id = 0
    froms.username = ""
    froms.realname = ""
    froms.phone = ""
    froms.roleIds = []
}


/**
 * 表单验证
 */
const rules = reactive({
    username: [
        { required: true, trigger: 'blur', message: "请输入用户名" }
    ],

    password: [
        { required: true, trigger: 'blur', message: "请输入密码" },
        { pattern: /^\w{6,15}$/, message: "请输入6-15位的密码" }
    ],
    phone: [
        { required: true, trigger: 'blur', message: "请输入您的手机号码！" },
        { pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/, message: "请正确填写您的手机号码" }
    ],
    realname: [
        { required: true, trigger: 'blur', message: "请输入真实姓名" },
        { pattern: /^[\u4e00-\u9fa5]{1,}$/, message: "请输入中文" }
    ],
    roleIds: [
        { required: true, trigger: 'blur', message: "角色不能为空" }
    ],
})
</script>
  

<style scoped lang="less">
.scrollbar-demo-item {
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: center;
}

.metaBox {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 60vh;
    text-align: center;
}

.fix_input {
    width: 200px;
}

.treechile {
    position: relative;
    right: 0px;
    color: red;
}
</style>